package com.tedu.weibo.exception;

import com.tedu.weibo.result.JsonResult;
import com.tedu.weibo.result.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException e)
    {
        System.out.println("参数不合法");
        return new JsonResult(Status.OPERATION_ERROR,e.getMessage());
    }

    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException e)
    {
        return new JsonResult(Status.OPERATION_ERROR,e.getMessage());
    }

    @ExceptionHandler
    public JsonResult doHandleException(Exception e){
        log.error(e.getMessage(),e);
        return new JsonResult(Status.UNKNOWN_ERROR);
    }

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String msg=e.getBindingResult().getFieldError().getDefaultMessage();
        log.warn(msg,e);
        return new JsonResult(Status.VALIDATE_FAILED,msg);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e){
        String msg = e.getMessage();
        msg=msg.substring(msg.indexOf(":")+1).trim();
        log.warn(msg,e);
        return new JsonResult(Status.VALIDATE_FAILED,msg);
    }
}
